import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class CallBackUtil {

    /**
     * 校验请求体签名是否正确
     *
     * @param backBody 请求体
     * @param token 消息校验token
     * @return
     */
    public static boolean checkCallBackBody(CallBackBody backBody,String token){
        StringBuilder sb=new StringBuilder();
        sb.append(backBody.getEncrypContent());
        sb.append(backBody.getTimeStamp());
        sb.append(backBody.getNonce());
        sb.append(token);
        String sign = DigestUtils.sha256Hex(sb.toString());
        return sign.equals(backBody.getSign());
    }


    /**
     *  对应请求内容进行解密
     *
     * @param base64Content
     * @param encryptPass
     * @return
     */
    public static String decrypt(String base64Content, String encryptPass) {
        byte[] content = Base64.decodeBase64(base64Content);
        if (content.length < 12 + 16) {
            throw new IllegalArgumentException();
        }
        GCMParameterSpec params = new GCMParameterSpec(128, content, 0, 12);
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(encryptPass), params);
            byte[] decryptData = cipher.doFinal(content, 12, content.length - 12);
            return new String(decryptData, Charsets.UTF_8);
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @param encryptPass 入参
     * @return 返回值
     * @author tWX995275
     * @since 2021/3/16 17:10
     */
    private static SecretKeySpec getSecretKey(String encryptPass) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        // 初始化密钥生成器，AES要求密钥长度为128位、192位、256位
        secureRandom.setSeed(encryptPass.getBytes());
        kg.init(128,secureRandom);
        SecretKey secretKey = kg.generateKey();
        // 转换为AES专用密钥
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    }

}
